<div id="app"></div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const { reactive, watchEffect, createApp, ref } = Vue;

  const useFetch = (getUrl) => {
    const data = ref(null);
    const loading = ref(true);
    const error = ref(null);
    watchEffect(() => {
      fetch(getUrl())
        .then((res) => {
          if (!res.ok) throw new Error(res.status);
          return res.json();
        })
        .then((_data) => {
          setTimeout(() => {
            data.value = _data;
            loading.value = false;
          });
        })
        .catch((err) => {
          error.value = err || "An unknown error occurred";
          loading.value = false;
        });
    });
    return { data, loading, error };
  };

  const Post = {
    template: `
      <div v-if='data'>{{data}}</div>
      <div v-if='loading'>loading....</div>
      <div v-if="error">{{error}}</div>
    `,
    props: ["id"],
    setup(props) {
      console.log(props);

      const url = () =>
        `https://jsonplaceholder.typicode.com/todos/${props.id}`;
      const { data, loading, error } = useFetch(url);
      return { data, loading, error };
    },
  };

  const App = {
    components: { Post, Emp },
    template: `
      <button @click.prevent="id++">chang ID + {{id}}</button> 
      <Post :id="id"/>
    `,
    setup() {
      const id = ref(1);
      return { id };
    },
  };

  createApp(App).mount("#app");
</script>
